import { defineStore } from "pinia";

import { Url } from "$/entity";

import { map } from "@/utils/ArrayUtil";
import LocalNameEnum from "@/enumeration/LocalNameEnum";
import Assert from "@/utils/Assert";
import { useIndexStore } from "@/store/index";
import { useKVStorage } from "@/hooks";
import { urlAdd, urlDelete, urlList, urlUpdate } from "@/api";
import { useUmami } from "@/plugins/umami";

const title = useTitle();

export const useUrlStore = defineStore("url", () => {
  const lastUrlId = useKVStorage(LocalNameEnum.KEY_LAST_URL, "");
  // state
  const urls = ref<Array<Url>>([]);
  const url = ref<Url>();

  // getters
  const urlMap = computed(() => map(urls.value, "id"));
  // 全部链接
  const list = computed(() => urls.value);
  // 当前链接
  const current = computed(() => url.value?.value || "");
  // 当前链接的ID
  const id = computed(() => (url.value ? url.value.id! : undefined));
  // 是否没有链接
  const empty = computed(() => url.value === undefined);
  // 是否是有效的链接
  const effective = computed(() => !empty.value);

  // actions
  const init = async () => {
    urls.value = await urlList();
  };

  init()
    .then(() => {
      console.log("url init successfully");

      // 最后的链接
      if (lastUrlId.value) {
        if (lastUrlId.value !== "0") {
          // 选择链接
          Assert.isTrue(choose(lastUrlId.value), "链接未找到");
          // 索引刷新
          useIndexStore().reset();
        }
      }
    })
    .catch((e) => console.error("url init failed", e));

  const choose = (id: string): boolean => {
    // 查询URL
    const targetUrl = urls.value.find((e) => e.id! === id);
    if (!targetUrl) {
      return false;
    }
    // 统计用户使用的es版本
    useUmami.track("es_version", targetUrl.version);
    lastUrlId.value = id;
    url.value = targetUrl;
    title.value = targetUrl.name || "es-client";
    return true;
  };

  const clear = () => {
    url.value = undefined;
    title.value = "es-client";
  };

  const add = async (record: Omit<Url, "id" | "createTime" | "updateTime">) => {
    await urlAdd(record);
    await init();
  };

  const update = async (id: string, record: Partial<Url>) => {
    await urlUpdate(id, record);
    await init();
  };

  const remove = async (id: string) => {
    await urlDelete(id);
    await init();
  };

  return {
    urls,
    url,
    urlMap,
    list,
    current,
    id,
    empty,
    effective,
    choose,
    clear,
    add,
    update,
    remove
  };
});
